/**
 *
 */
package jp.seraph.jsade.task;

import java.util.Iterator;

import jp.seraph.jsade.core.Player;
import jp.seraph.jsade.core.World;
import jp.seraph.jsade.util.Executor;

/**
 *
 *
 */
public abstract class EnumerableTask extends AbstractTask {
    private Iterator<AgentTask> mTasks;
    private AgentTask mCurrentTask;

    protected void initialize(Iterator<AgentTask> aTasks){
        if(aTasks.hasNext()){
            mTasks = aTasks;
            mCurrentTask = mTasks.next();
            initialize(mCurrentTask);
        }
        else{
            mTasks = null;
        }
    }

    private void initialize(AgentTask aTask){
        Executor tExecuter = new Executor(){
            public void execute(){
                if(mTasks.hasNext()){
                    AgentTask tTask = mTasks.next();
                    initialize(tTask);
                    mCurrentTask = tTask;
                }else{
                    mTasks = null;
                    mCurrentTask = null;
                }
            }
        };

        aTask.addCompletedListener(tExecuter);
        aTask.addCanceledListener(tExecuter);
        aTask.init();
    }

    /**
     *
     * @see jp.seraph.jsade.task.AbstractTask#execute(jp.seraph.jsade.core.World, jp.seraph.jsade.core.Player)
     */
    @Override
    public void execute(World aWorld, Player aPlayer) {
        if(mTasks == null){
            complete();
            return;
        }

        mCurrentTask.execute(aWorld, aPlayer);
    }

    /**
     *
     * @see jp.seraph.jsade.task.AgentTask#cancel()
     */
    public void cancel() {
        if(mCurrentTask != null){
            mCurrentTask.cancel();
        }

        super.cancel();
    }
}
